<!--
 * @Author: 吴竹叶 2107206923@qq.com
 * @Date: 2023-09-27 16:02:37
 * @LastEditors: 吴竹叶 2107206923@qq.com
 * @LastEditTime: 2023-10-17 17:28:18
 * @FilePath: \BZ_JT_AnQuanHuanBaoGuanLiApp\src\views\staging\commom\statistics\safetyStatistic.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="energy-wrap">
    <div class="firms-box">
      <customTitle :is-icon="true" icon="&#xe791;" bg-color="#07cdd4" icon-color="#07cdd4" title="能源综合看板">
        <template #right>
          <custom-timer type="year" :is-interval="false" :is-title="false" :is-border="false" :date-value.sync="year" @change="getData" />
        </template>
      </customTitle>
      <div class="firms-content content-box">
        <ul>
          <li v-for="(it, ind) in energyData" :key="ind">
            <span class="name">{{ it.name }}</span>
            <b>{{ data[it.field] }}{{ it.unit }}</b>
          </li>
        </ul>
      </div>
    </div>
    <customTitle :is-line="true" bg-color="#3795ff" title="用能结构分析" />
    <div ref="pieChart" class="pieChart-area" style="height: 251px;text-align: center;" />
    <customTitle :is-line="true" bg-color="#3795ff" title="能耗分析TOP5" />
    <div ref="barChart" class="barChart-area" style="height: 251px;" />
  </div>
</template>

<script>
import customTitle from '@/components/globals/custom-title.vue'
import customTimer from '@/components/common/custom-timer.vue'
import { lineHorizontalChart, pieChart } from '@/utils/chart'
import { parseTime } from '@/utils'
import {
  cleanerProductionTypeNum,
  energyCertifyByCompanyNum,
  getByCompany,
  getEnergyUsage,
  getExpertStatistics,
  getHomeData,
  getImportEnergyStatistic,
  getNySynthesisCostList,
  greenFactorTypeNum,
  projectsTypeNum,
  quaeterFillYearSum
} from '@/api/commonPage/energySourcesStatistics'
import commonList from '@/assets/mixin/commonList'

export default {
  inject: ['layout'],
  components: {
    customTitle,
    customTimer
  },
  mixins: [commonList],
  data() {
    return {
      energyData: [
        { unit: '', name: '能源消费量', field: 'guidefirst1' },
        { unit: '万吨标准煤', name: '综合能源消费量', field: 'guidefirst2' },
        { unit: '', name: '万元产值综合能耗', field: 'guidefirst3' },
        { unit: '', name: '工业总产值', field: 'guidefirst4' },
        { unit: '家', name: '通过能源管理体系认证企业', field: 'energyCertifyNum' },
        { unit: '家', name: '重点用能单位', field: 'energyCompanyNum' },
        { unit: '个', name: '合同能源管理项目', field: 'contrac' },
        { unit: '个', name: '光伏项目', field: 'photovoltaic' },
        { unit: '个', name: '清洁生产项目', field: 'cleanerProductionNum' },
        { unit: '个', name: '绿色工厂', field: 'greenFactorNum' },
        { unit: '人', name: '本年度在聘专家数量', field: 'expertNum' }
      ],
      year: parseTime(new Date(), '{y}'),
      apiNum: 0,
      loadNum: 0,
      data: {
        guidefirst1: '',
        guidefirst2: '',
        guidefirst3: '',
        guidefirst4: '',
        energyCertifyNum: '',
        energyCompanyNum: '',
        contrac: '',
        photovoltaic: '',
        cleanerProductionNum: '',
        greenFactorNum: '',
        expertNum: ''
      },
      pieChartData: [],
      barChartData: []
    }
  },
  mounted() {
    this.layout.showAreaLoading(['.firms-box', '.pieChart-area', '.barChart-area'])
    this.getData()
  },
  methods: {
    getData() {
      this.quaeterFillYearSum()
      this.getNySynthesisCostList()
      this.energyCertifyByCompanyNum()
      this.getImportEnergyStatistic()
      this.projectsTypeNum()
      this.cleanerProductionTypeNum()
      this.greenFactorTypeNum()
      this.getExpertStatistics()
      // 能耗分析TOP5
      this.getHomeData()
      // this.getByCompany()
      // 用能结构分析
      this.getEnergyUsage()
      // PC端未使用此接口
      // this.getHomeData()
    },
    closeLoading() {
      this.loadNum++
      if (this.loadNum >= this.apiNum) {
        this.layout.hideAreaLoading(['.firms-box', '.pieChart-area', '.barChart-area'])
      }
    },
    // 能源综合看板
    async quaeterFillYearSum() {
      this.apiNum++
      const { status, data } = await quaeterFillYearSum({ companyId: -1, year: this.year })
      if (status === 0 && data) {
        this.data.guidefirst1 = data.find(val => val.targetname === '能源消费量')?.currentyear
        this.data.guidefirst2 = data.find(val => val.targetname === '综合能源消费量')?.currentyear.split(' ')[0]
        this.data.guidefirst3 = data.find(val => val.targetname === '万元产值综合能耗')?.currentyear
        this.data.guidefirst4 = data.find(val => val.targetname === '工业总产值')?.currentyear
      }
      this.closeLoading()
    },
    // 综合能源消费量
    async getNySynthesisCostList() {
      this.apiNum++
      const { status, data } = await getNySynthesisCostList({ years: this.year })
      if (status === 0 && data) {
        // this.data.guidefirst2 = Number(data).toFixed(4)
      }
      this.closeLoading()
    },
    // 能耗分析TOP5  这个才是对的！
    async getHomeData() {
      this.apiNum++
      const { status, data } = await getHomeData({ years: this.year })
      if (status === 0 && data) {
        this.barChartData = data
        this.initBarChart()
        // const guidefirst1 = data.find(val => val.name === '能源消费量')?.currentq
        // const guidefirst3 = data.find(val => val.name === '万元产值综合能耗')?.currentq
        // this.data.guidefirst1 = Number((guidefirst1 || '0')).toFixed(4) + ' 万吨标准煤'
        // this.data.guidefirst3 = Number((guidefirst3 || '0')).toFixed(4) + ' 吨标准煤／万元'
      }
      this.closeLoading()
    },
    // 通过能源管理体系认证企业
    async energyCertifyByCompanyNum() {
      this.apiNum++
      const { status, data } = await energyCertifyByCompanyNum({ companyIds: -1, years: this.year })
      if (status === 0 && data) {
        this.data.energyCertifyNum = data.find(val => val.key === 'sum')?.val
      }
      this.closeLoading()
    },
    // 重点用能单位
    async getImportEnergyStatistic() {
      this.apiNum++
      const { status, data } = await getImportEnergyStatistic({ companyIds: -1, years: this.year })
      if (status === 0 && data) {
        this.data.energyCompanyNum = data.countTotal
      }
      this.closeLoading()
    },
    // 光伏项目 合同能源项目
    async projectsTypeNum() {
      this.apiNum++
      const { status, data } = await projectsTypeNum({ companyIds: -1, years: this.year })
      if (status === 0 && data) {
        this.data.photovoltaic = data.photovoltaic
        this.data.contrac = data.contrac
      }
      this.closeLoading()
    },
    // 清洁生产项目
    async cleanerProductionTypeNum() {
      this.apiNum++
      const { status, data } = await cleanerProductionTypeNum({ companyIds: -1, years: this.year })
      if (status === 0 && data) {
        this.data.cleanerProductionNum = data.find(val => val.key === '清洁生产项目')?.val
      }
      this.closeLoading()
    },
    // 绿色工厂
    async greenFactorTypeNum() {
      this.apiNum++
      const { status, data } = await greenFactorTypeNum({ companyIds: -1, years: this.year })
      if (status === 0 && data) {
        this.data.greenFactorNum = data.find(val => val.key === '绿色工厂数量')?.val
      }
      this.closeLoading()
    },
    // 在聘专家数量
    async getExpertStatistics() {
      this.apiNum++
      const { status, data } = await getExpertStatistics({ companyId: -1, years: this.year })
      if (status === 0 && data) {
        this.data.expertNum = data.expertTotal
      }
      this.closeLoading()
    },
    // 能耗分析TOP5
    async getByCompany() {
      this.apiNum++
      const { status, data } = await getByCompany({ years: this.year, pageNum: 1, pageSize: 5 })
      if (status === 0 && data) {
        this.barChartData = data
        this.initBarChart()
      }
      this.closeLoading()
    },
    initBarChart() {
      const data = this.barChartData
      const dataY = data.map((val) => val.name).reverse()
      const dataSeries = [
        {
          name: '用电消耗量',
          type: 'bar',
          stack: 1,
          data: data.map((val) => Number(val.power)).reverse(),
          itemStyleColor: '#5B8FF9'
        }, {
          name: '天然气消耗量',
          type: 'bar',
          stack: 1,
          data: data.map((val) => Number(val.naturalGas)).reverse(),
          itemStyleColor: '#52D6A2'
        }, {
          name: '热力消耗量',
          type: 'bar',
          stack: 1,
          data: data.map((val) => Number(val.thermodynamics)).reverse(),
          itemStyleColor: '#5D7092'
        }, {
          name: '光伏发电消耗量',
          type: 'bar',
          stack: 1,
          data: data.map((val) => Number(val.photovoltaic)).reverse(),
          itemStyleColor: '#F5BB0E'
        }
      ]
      const params = {
        legendShow: false,
        tooltipShow: true,
        gridRight: '5%',
        gridTop: '12%',
        gridLeft: '0%',
        gridBottom: '12%',
        legendBottom: 1,
        xAxisName: '万吨标准煤',
        formatterFun(value) {
          return value
        }
      }
      const chart = this.$refs.barChart
      if (chart) {
        if (dataY.length > 0) {
          const myChart = this.$echarts.init(chart)
          myChart.setOption(lineHorizontalChart(dataY, dataSeries, params))
          this.setLegend(chart, myChart)
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    },
    // 用能结构分析
    async getEnergyUsage() {
      this.apiNum++
      const { status, data } = await getEnergyUsage({ years: this.year, companyId: -1 })
      if (status === 0 && data) {
        this.pieChartData = data
        this.initPieChart()
      }
      this.closeLoading()
    },
    initPieChart() {
      const colorList = ['#5B8FF9', '#52D6A2', '#5D7092', '#F5BB0E', '#6F5EF9']
      // 剔除数据为0的和用能结构
      const data = this.pieChartData.filter(v => {
        return v.name !== '能源消费量' && v.name !== '用能结构占比'
      })
      const currentq = this.pieChartData.find(val => val.name === '用能结构占比')?.currentq
      const dataList = data.map((v, i) => {
        return {
          value: v.currentq,
          name: v.name,
          itemStyle: { color: colorList[i] },
          label: {
            color: '#333',
            position: 'outside',
            formatter: (params) => {
              const data = params.data
              if (Number(data.value) === 0) {
                data.labelLine = { show: false }
                data.label.show = false
              } else {
                return `${params.percent}%`
              }
              return `${params.percent}%`
            }
          }
        }
      })
      const dataSeries = [
        {
          name: '用能结构分析',
          radius: ['50%', '70%'],
          center: ['50%', '46%'],
          data: dataList,
          percentPrecision: 2
        }
      ]
      const total = data.reduce((previousValue, currentValue, currentIndex, array) => previousValue + Number(currentValue.currentq), 0)
      const params = {
        tooltipShow: true,
        legendShow: true,
        legendBottom: 0,
        legendWidth: 18,
        legendHeight: 12,
        titleShow: true,
        legendLeft: 'center',
        titleText: currentq + '\n万吨标准煤',
        titleX: '48%',
        titleY: '36%',
        titleColor: '#333',
        titleTextAlign: 'center',
        tooltipFormatter: (params) => {
          return `${params.seriesName}<br/>${params.marker}${params.name}：${params.value}(${params.percent}%)<br/>`
        }
      }
      const chart = this.$refs.pieChart
      if (chart) {
        if (total > 0) {
          const myChart = this.$echarts.init(chart)
          const options = pieChart(params, dataSeries)
          myChart.setOption(options, true)
          window.addEventListener('resize', () => {
            myChart.resize()
          })
        } else {
          this.layout.chartNoData(chart)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .energy-wrap {
    background-color: #fff;
    .content-box {
      padding: 10px;
      background-color: #e5feff;
      border-radius: 10px;
      border: solid 2px #07cdd4;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      ul {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        li {
          width: 100%;
          display: flex;
          justify-content: space-between;
          height: 50px;
          background-color: rgba(139, 220, 223, 0.5);
          border-left: solid 2px #07cdd4;
          border-right: solid 2px #07cdd4;
          margin: 5px 5px;
          align-items: center;
          padding: 0 10px;
          font-size: 0.373rem;
          color: #051b32;
          position: relative;
          &:nth-child(5) {
            width: 100%;
          }
          &:nth-child(6) {
            width: 100%;
          }
          &:nth-child(7) {
            width: 100%;
          }
          &::before {
            content: '';
            width: 100%;
            height: 1px;
            border-left: 6px solid #07cdd4;
            border-right: 6px solid #07cdd4;
            position: absolute;
            top: 0;
            left: 0;
          }
          &::after {
            content: '';
            width: 100%;
            height: 1px;
            border-left: 6px solid #07cdd4;
            border-right: 6px solid #07cdd4;
            position: absolute;
            bottom: 0;
            left: 0;
          }
        }
      }
      &.danger-content {
        background-color: #cedeff;
        border: solid 2px #6a99f9;
        .total {
          width: 42%;
          display: flex;
          flex-direction: row;
          justify-content: flex-start;
          position: relative;
          padding-left: 0.267rem;
          align-items: center;
          &::before {
            content: '';
            left: 0;
            height: 0.373rem;
            width: 0.106rem;
            position: absolute;
            top: 0.187rem;
            background-color: #6a99f9;
          }
          h3 {
            color: #6a99f9;
            margin-left: 0.133rem;
          }
        }
        ul {
          width: 58%;
          li {
            width: calc(50% - 10px);
            background-color: rgba(159, 189, 248, 0.5);
            border-left: solid 2px #6a99f9;
            border-right: solid 2px #6a99f9;
            div {
              display: flex;
              width: 30%;
            }
            &::before {
              border-left: 6px solid #6a99f9;
              border-right: 6px solid #6a99f9;
            }
            &::after {
              border-left: 6px solid #6a99f9;
              border-right: 6px solid #6a99f9;
            }
          }
        }
        &.danger-content1 {
          background-color: #c3eadd;
          border: solid 2px #42d7a7;
          .total {
            width: 42%;
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            position: relative;
            padding-left: 0.267rem;
            align-items: center;
            &::before {
              content: '';
              left: 0;
              height: 0.373rem;
              width: 0.106rem;
              position: absolute;
              top: 0.187rem;
              background-color: #42d7a7;
            }
            h3 {
              color: #42d7a7;
              margin-left: 0.133rem;
            }
          }
          ul {
            width: 58%;
            li {
              width: calc(50% - 10px);
              background-color: rgba(136, 230, 200, 0.5);
              border-left: solid 2px #42d7a7;
              border-right: solid 2px #42d7a7;
              p {
                width: 100%;
              }
              div {
                display: flex;
                width: 30%;
              }
              &::before {
                border-left: 6px solid #42d7a7;
                border-right: 6px solid #42d7a7;
              }
              &::after {
                border-left: 6px solid #42d7a7;
                border-right: 6px solid #42d7a7;
              }
            }
          }
        }
      }
    }
    .customTimer {
      margin: 0;
      width: 2.133rem;
      border: 1px solid #3795ff;
      border-radius: 0.106rem;
      ::v-deep .timer-box .down {
        color: #3795ff;
      }
    }
  }
</style>
